package com.itts.middle.config.cros;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CrosFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;

        HttpServletRequest req = (HttpServletRequest) request;

        //获取请求中的Origin地址
        String origin = req.getHeader("Origin");
        if (!StringUtils.isEmpty(origin)) {
            //带cookie时不能为*
            res.addHeader("Access-Control-Allow-Origin", origin);
        }

        res.addHeader("Access-Control-Allow-Methods", "*");
        //非简单请求 预检
        res.addHeader("Access-Control-Allow-Headers",
                "ResponseType,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With,Token,x-access-token,ContentType"
        );
        //缓存
        res.addHeader("Access-Control-Max-Age", "3600");
        //cookie
        res.addHeader("Access-Control-Allow-Credentials", "true");

        //自定义头
        String headers = req.getHeader("Access-Control-Request-Headers");
        if (!StringUtils.isEmpty(headers)) {
            res.addHeader("Access-Control-Allow-Headers", headers);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }


}
